package dp.mobile.comm.worker;

import java.io.IOException;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.util.Log;

class Acceptor extends WorkerBase {
	private BluetoothServerSocket mServerSocket;
	
	public Acceptor(BluetoothAdapter adapter , BluetoothHandler handler) {
		super(handler);
		BluetoothServerSocket tmp = null;

		Log.i("this" , "Acceptor running");
        // Create a new listening server socket
        try {
            tmp = adapter.listenUsingRfcommWithServiceRecord(EDEN_NAME, EDEN_UUID);
        } catch (IOException e) {
            //Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
        }
        mServerSocket = tmp;
	}
	
	@Override
	public void run() {
		Log.i("this" , "ACCEPTOR NOT RUNNING");
		if (mServerSocket != null) {
			Log.i("this" , "ACCEPTOR RUNNING");
			try {
				mSocket = mServerSocket.accept();
				/*mHandler.setConnectedSocket(mSocket);
				if (mEventHandler != null) mEventHandler.onConnected();*/
				mHandler.connected(mSocket);
				mServerSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				//if (mEventHandler != null && !mCanceled) mEventHandler.onAcceptFailed();
				if (!mCanceled) mHandler.listenFailed();
			}
			
			/*try {
				mServerSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		}
	}
	
	@Override
	public void cancel() {
		// TODO Auto-generated method stub
		if (mServerSocket != null) {
			mCanceled = true;
	        try {
	        	mServerSocket.close();
	            Log.i("this" , "CLOSING");
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
		}
	}

}
